package com.itheima.service.impl.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.dao.OrderDetailDao;
import com.itheima.dao.OrdersDao;
import com.itheima.domain.*;
import com.itheima.dto.DishDto;
import com.itheima.exception.NoDataException;
import com.itheima.service.*;
import com.itheima.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j

public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private OrderDetailDao orderDetailDao;

    //todo:需要设置各个字段的数据然后提交,在总金额这个地方需要通过订单明细表获取,
    //todo:这里就需要从购物车获取number name 存入明细表 amount存入订单表,
    //todo:最后再将所有的主从表保存就可以了.可能需要在从表加上时间点
    @Override
    public boolean submit(Orders orders) {
        //获得当前用户id
        String userId = TokenHolder.getCurrentId();

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            log.info("购物车为空,不能下单");
            return false;
        }
//
        //查询用户数据
        User user = userService.getById(userId);

        String userName = user.getName();
        String phone = user.getPhone();
        //查询地址数据
        String addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            log.info("用户地址信息有误，不能下单");
            return false;
        }
        //计算总金额
        BigDecimal amount = new BigDecimal(0 + "");
        for (ShoppingCart shoppingCart : shoppingCarts) {
            BigDecimal numberDecimal = new BigDecimal(shoppingCart.getNumber());
            amount = amount.add(new BigDecimal(shoppingCart.getAmount()).multiply(numberDecimal));
        }

        orders.setStatus(orders.getStatus());
        orders.setUserId(userId);
        orders.setAddressBookId(orders.getAddressBookId());
        orders.setOrderTime(LocalDateTime.now() + "");
        orders.setCheckoutTime(LocalDateTime.now() + "");
        orders.setPayMethod(orders.getPayMethod());


        orders.setAmount(amount);
        orders.setRemark(orders.getRemark());
        orders.setUserName(userName);
        orders.setPhone(phone);
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        ;
        orders.setConsignee(addressBook.getConsignee());

        this.save(orders);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setUserId(userId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setOrderId(orders.getId());
            if (item.getDishId() != null) {
                orderDetail.setDishId(item.getDishId());
            }
            if (item.getSetmealId() != null) {
                orderDetail.setSetmealId(item.getSetmealId());
            }
            if (item.getDishFlavor() != null) {
                orderDetail.setDishFlavor(item.getDishFlavor());
            }
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(new BigDecimal(item.getAmount()));
            return orderDetail;
        }).collect(Collectors.toList());

        for (OrderDetail orderDetail : orderDetails) {
            orderDetailService.save(orderDetail);
        }
        //清空购物车数据
        shoppingCartService.remove(wrapper);
        return true;
    }


//    @Override
//    public Page userPage(int page, int pageSize) {
//        Page<Orders> ordersPage = new Page<>(page, pageSize);
//        Page<OrderVo> pageInfo = new Page<>();
//        long userId = Long.parseLong(TokenHolder.getCurrentId());
//        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Orders::getUserId,userId);
//        wrapper.orderByDesc(Orders::getOrderTime);
//        ordersPage = this.page(ordersPage, wrapper);
//
//        BeanUtils.copyProperties(ordersPage, pageInfo, "records");
//
//        List<Orders> orders = ordersPage.getRecords();
//        List<OrderVo> ordersVos = orders.stream().map((order) -> {
//            OrderVo ordersVo = new OrderVo();
//            BeanUtils.copyProperties(order, ordersVo);
//            List<OrderDetail> orderDetails = orderDetailService.getById(ordersVo.getId);;
//
//            ordersVo.setOrderDetails(orderDetails);
//            return ordersVo;
//        }).collect(Collectors.toList());
//
//        pageInfo.setRecords(ordersVos);
//        return pageInfo;
//    }
     @Override
     public Page userPage(Integer page, Integer pagesize) {
        Page<Orders> ordersPage = new Page<>(page, pagesize);
        Page<OrderVo> pageInfo = new Page<>(page, pagesize);
        long userId = Long.parseLong(TokenHolder.getCurrentId());
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,userId)
                .orderByDesc(Orders::getOrderTime);
        ordersPage = this.page(ordersPage, wrapper);

        BeanUtils.copyProperties(ordersPage, pageInfo, "records");

        List<Orders> orders = ordersPage.getRecords();
        List<OrderVo> ordersVos = orders.stream().map((order) -> {
            OrderVo ordersVo = new OrderVo();
            BeanUtils.copyProperties(order, ordersVo);
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(wrapper1);
            ordersVo.setOrderDetails(orderDetails);
            return ordersVo;
        }).collect(Collectors.toList());

        pageInfo.setRecords(ordersVos);
        return pageInfo;
    }
//    @Override
//    public List<OrderVo> userPage(Integer page, Integer pageSize) {
//        Page page1 = new Page<>(page,pageSize);
//        QueryWrapper wrapper = new QueryWrapper();
//
//        page1=ordersDao.selectPage(page1,wrapper);
//        //取出查询的集合列表
//        List<Orders> orderList = page1.getRecords();
//        List<OrderVo> orderVos = new ArrayList<>();
//
//        for (Orders orders : orderList) {
//            OrderVo orderVo = new OrderVo();
//            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
//            wrapper1.eq(OrderDetail::getUserId,TokenHolder.getCurrentId())
//                    .eq(OrderDetail::getOrderId,orders.getId());
//            List<OrderDetail> orderDetails = orderDetailService.list(wrapper1);
//            //复制对象
//            BeanUtils.copyProperties(orders,orderVo);
//            orderVo.setFlavors(orderDetails);
//
//            orderVos.add(orderVo);
//
//        }
//        page1.setRecords(orderVos);
//        return  orderVos;
//    }

    @Override
    public boolean updateState(Map map) {
        String status = map.get("status").toString();
        String id = map.get("id").toString();

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId,id);
        Orders orders = this.getOne(queryWrapper);
        //修改state字段设置
        orders.setStatus(status);
        this.updateById(orders);
        return true;
    }

    @Override
    public List<OrderVo> selectPage(String number, Integer page, Integer pageSize) {
        Page page1 = new Page<>(page,pageSize);
        QueryWrapper wrapper = new QueryWrapper();

        page1=ordersDao.selectPage(page1,wrapper);
        //取出查询的集合列表
        List<Orders> ordersPage = page1.getRecords();
        List<OrderVo> ordersList = new ArrayList<>();

//        Set<String> categoryIds =new HashSet<>();

        for (Orders orders : ordersPage) {
            OrderVo ordervo  = new OrderVo();
            //复制对象
            BeanUtils.copyProperties(orders,ordervo);
            ordersList.add(ordervo);
            //由于建表原因,如果需要修改字段,则需引入下面这段,从id再获取到名字,最后再存入
            //口味表,这里就不添加,如果有需要再回来做修改
//            String categoryId = dishDto.getCategoryId();
//            categoryIds.add(categoryId);
        }
        page1.setRecords(ordersList);
        return ordersList;
    }
}




